// 获取用户登录的信息
function getUserMessage() {
    let userMessage = JSON.parse(localStorage.getItem('userDataInformation'))
    if (userMessage) {
        let str = `
                    <li><img src="${userMessage[0].headPortrait}" alt=""></li>
                    <li>${userMessage[0].userName}</li>
                `
        $('#headerTop .headerTopUserMessage').html(str)
    } else {
        let str = `
                    <li>未登录</li>
                `
        $('#headerTop .headerTopUserMessage').html(str)
    }
}

// 搜索展开部分
function unSearch() {
    $('#header>.search>img').on('click', function () {
        $('#header>.searchPro').animate({
            width: 'toggle'
        }, 350)
    })
}

// 搜素功能
function searchPro() {
    let count
    $('#header>.searchPro>input').on('keydown', function (e) {
        let keyCode = e.keyCode || e.which
        if (keyCode == 13) {
            $.ajax({
                url: 'http://www.xiongmaoyouxuan.com/api/search',
                type: 'get',
                data: {
                    word: $('#header>.searchPro>input').val()
                },
                success: function (data) {
                    let Arr = data.data.list
                    if (Arr.length % 4 == 0) {
                        count = Arr.length
                    } else {
                        count = Arr.length - Arr.length % 4
                    }
                    goodsList(Arr.slice(0, count))
                },
                error: function (err) {
                    alert("网络请求失败：" + err)
                }
            })
        }
    })
}

// 顶部商品名称展示商品图片
function hearderProNameToShowProNav() {
    $('#header .proNameNav li').on('mouseover', function () {
        $(this).css('cursor', 'pointer')
    })
    $('#header .proNav').css('display', 'none')
    $('#header .proNameNav li').on('click', function () {
        $(this).css('cursor', 'pointer')
        $('#header .proNav').slideToggle(1000)
        if ($(this).index() == 0) {
            $.ajax({
                url: 'http://quan.lukou.com/api/tab/2?start=0',
                type: 'get',
                success: function (data) {
                    headerProNav(data.data.hotCommodities)
                },
                error: function (err) {
                    alert("网络请求失败：" + err)
                }
            })
        }
        if ($(this).index() == 1) {
            $.ajax({
                url: 'http://quan.lukou.com/api/tab/4?start=0',
                type: 'get',
                success: function (data) {
                    headerProNav(data.data.items.list)
                },
                error: function (err) {
                    alert("网络请求失败：" + err)
                }
            })
        }
        if ($(this).index() == 2) {
            $.ajax({
                url: 'http://quan.lukou.com/api/tab/10?start=0',
                type: 'get',
                success: function (data) {
                    headerProNav(data.data.items.list)
                },
                error: function (err) {
                    alert("网络请求失败：" + err)
                }
            })
        }
        if ($(this).index() == 3) {
            $.ajax({
                url: 'http://quan.lukou.com/api/tab/12?start=0',
                type: 'get',
                success: function (data) {
                    headerProNav(data.data.items.list)
                },
                error: function (err) {
                    alert("网络请求失败：" + err)
                }
            })
        }
        if ($(this).index() == 4) {
            $.ajax({
                url: 'http://quan.lukou.com/api/tab/11?start=0',
                type: 'get',
                success: function (data) {
                    headerProNav(data.data.items.list)
                },
                error: function (err) {
                    alert("网络请求失败：" + err)
                }
            })
        }
    })
}

// 顶部渲染商品图片信息
function headerProNav(proNavList) {
    let proArr = proNavList.map(item => {
        return `
                <div class="proNavItem">
                    <div class="proNavItemImg">
                        <img src="${item.image}" alt="">
                    </div>
                    <span>${item.title}</span>
                </div>
                `
    }).join('')
    $('#header .proNav').html(proArr);
}

// 获取传来的商品id值
function proDetailId() {
    let url = location.href
    let proId = url.substring(url.indexOf('?') + 1)
    proId = proId.split('=')[1]
    return proId
}

//接口获取商品详情
function proDetail() {
    let id = proDetailId()
    $.ajax({
        url: 'http://www.xiongmaoyouxuan.com/api/detail',
        type: 'get',
        data: {
            id: id
        },
        success: function (data) {
            proDetailShow(data.data)

            //创建保存商品详情信息
            // 将商品详情信息存到对象中
            let proDetailPro = {
                id: data.data.detail.id,
                name: data.data.share.title,
                imgUrl: data.data.share.imageUrl,
                price: data.data.detail.price
            }
            addShoppingCart(proDetailPro)
        },
        error: function (error) {
            alert("网络请求失败：" + error)
        }
    })
}

// 展示渲染商品详细信息数据
function proDetailShow(proOnlyDetail) {
    let str = `
                <div class="proLeft clearfix fl">
                    <div class="proTop fl">
                        <img src="${proOnlyDetail.share.imageUrl}" alt="">
                        <div class="proMask"></div>
                    </div>
                    <ul class="proBottom">
                        <li><img src="${proOnlyDetail.detail.photo[0].url}" alt=""></li>
                        <li><img src="${proOnlyDetail.detail.photo[1].url}" alt=""></li>
                        <li><img src="${proOnlyDetail.detail.photo[2].url}" alt=""></li>
                        <li><img src="${proOnlyDetail.detail.photo[3].url}" alt=""></li>
                    </ul>
                    <!-- 放大镜区域 -->
                    <div class="magnifyingGlass none">
                        <img src="${proOnlyDetail.share.imageUrl}" alt="">
                    </div>
                    <div class="proMessage fl clearfix">
                        <h1>
                            <img class="tianmao" src="../static/images/tianmao.png" alt="">
                            <img class="baoyou" src="../static/images/baoyou.png" alt="">
                            ${proOnlyDetail.share.title}
                        </h1>
                        <div class="proJuan">
                            <div class="proOriginalPrice">原价￥${proOnlyDetail.detail.originPrice}</div>
                            <div class="proVolumePrice">
                                <span class="priceMessage">
                                    <span style="color: #ff4653;font-size: 20px;">卷后价:</span>
                                    <span style="font-size: 20px;color: #fa585a;font-weight: bold;">￥</span>
                                    <span style="font-size: 30px;color: #fa585a;font-weight: bold;">${parseInt(proOnlyDetail.detail.price)}</span>
                                    <span style="font-size: 25px;color: #fa585a;font-weight: bold;">.${((proOnlyDetail.detail.price).toString()).substring(((proOnlyDetail.detail.price).toString()).indexOf('.')+1)}</span>
                                </span>
                                <span class="Juan">${proOnlyDetail.detail.couponValue}</span>
                                <span class="personNum">${proOnlyDetail.detail.saleNum}人已购买</span>
                            </div>
                        </div>
                        <div class="protimeLimit">优惠有效期：${proOnlyDetail.detail.coupon.expireDate}</div>
                        <button class="buyNow">领卷购买</button>
                        <button class="addShoppingCart">加入购物车</button>
                    </div>
                </div>
                <div class="proRight fr">
                    <div class="sellerMessage">
                        <span class="line"></span>
                        <span class="txt">卖家信息</span>
                        <span class="line"></span>
                    </div>
                    <img src="${proOnlyDetail.shop.picUrl}" alt="">
                    <p class="shopName">${proOnlyDetail.shop.nickname}</p>
                    <div class="shopScore">
                        <ul class="character">
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(0,2)}</li>
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(6,8)}</li>
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(12,14)}</li>
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(19,23)}</li>
                        </ul>
                        <ul class="score">
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(2,5)}</li>
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(8,11)}</li>
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(14,17)}</li>
                            <li>${(proOnlyDetail.shop.shopScoreText).substring(23,27)}</li>
                        </ul>
                    </div>
                </div>
            `
    $('#proDetail').html(str)

    InsetsSwitch()
    mouseEvents()
    salce()
}

// 点击小图标切换大图
function InsetsSwitch() {
    $('#proDetail .proLeft .proBottom li').on('click', function () {
        $('#proDetail .proLeft .proTop>img').prop('src', $(this).children().attr('src'))
        $('#proDetail .proLeft .magnifyingGlass>img').prop('src', $(this).children().attr('src'))
    })
}

//鼠标移动事件，遮罩层
function mouseEvents() {
    //鼠标移入事件
    $('#proDetail .proLeft .proTop').mouseover(function () {
        $('#proDetail .proLeft .proTop .proMask').css('display', 'block')
        $('#proDetail .proLeft .magnifyingGlass').removeClass('none')
    })
    //鼠标移出事件
    $('#proDetail .proLeft .proTop').mouseout(function () {
        $('#proDetail .proLeft .proTop .proMask').css('display', 'none')
        $('#proDetail .proLeft .magnifyingGlass').addClass('none')
    })
    //鼠标移动事件
    $('#proDetail .proLeft .proTop').mousemove(function (e) {
        e = e || window.event
        let x = e.offsetX - $('#proDetail .proLeft .proTop .proMask').width() / 2
        let y = e.offsetY - $('#proDetail .proLeft .proTop .proMask').height() / 2
        if (x < 0) {
            x = 0
        }
        if (y < 0) {
            y = 0
        }
        if (x > $('#proDetail .proLeft .proTop').width() - $('#proDetail .proLeft .proTop .proMask').width()) {
            x = $('#proDetail .proLeft .proTop').width() - $('#proDetail .proLeft .proTop .proMask').width()
        }
        if (y > $('#proDetail .proLeft .proTop').height() - $('#proDetail .proLeft .proTop .proMask').height()) {
            y = $('#proDetail .proLeft .proTop').height() - $('#proDetail .proLeft .proTop .proMask').height()
        }
        $('#proDetail .proLeft .proTop .proMask').css({
            top: y + 'px',
            left: x + 'px'
        })

        //放大镜图片位置
        //放大镜盒子宽度
        let glassBoxW = $('#proDetail .proLeft .magnifyingGlass').width()
        //遮罩层宽度
        let maskW = $('#proDetail .proLeft .proTop .proMask').width()

        //放大镜盒子高度
        let glassBoxH = $('#proDetail .proLeft .magnifyingGlass').height()
        //遮罩层高度
        let maskH = $('#proDetail .proLeft .proTop .proMask').height()

        //放大背景图的移动距离
        let bgImgMoveW = x * glassBoxW / maskW
        let bgImgMoveH = y * glassBoxH / maskH
        $('#proDetail .proLeft .magnifyingGlass>img').css({
            top: `-${bgImgMoveH}px`,
            left: `-${bgImgMoveW}px`
        })
    })
}

//计算放大图片的大小事件
function salce() {
    //show盒子宽度
    let showItemBoxW = $('#proDetail .proLeft .proTop').width()
    //放大镜盒子宽度
    let glassBoxW = $('#proDetail .proLeft .magnifyingGlass').width()
    //遮罩层宽度
    let maskW = $('#proDetail .proLeft .proTop .proMask').width()

    //show盒子高度
    let showItemBoxH = $('#proDetail .proLeft .proTop').height()
    //放大镜盒子高度
    let glassBoxH = $('#proDetail .proLeft .magnifyingGlass').height()
    //遮罩层高度
    let maskH = $('#proDetail .proLeft .proTop .proMask').height()

    //设置放大镜背景图等比例大小
    $('#proDetail .proLeft .magnifyingGlass>img').width(`${showItemBoxW*glassBoxW/maskW}px`)
    $('#proDetail .proLeft .magnifyingGlass>img').height(`${showItemBoxH*glassBoxH/maskH}px`)
}

// 加入购物车按钮事件
function addShoppingCart(proDetailPro) {
    $('#proDetail .proLeft .proMessage .addShoppingCart').on('click', function () {
        if ($('#headerTop .headerTopUserMessage li').html()=='未登录') {
            location.href = '../pages/login.html'
            return
        }
        let shoppingArr = JSON.parse(localStorage.getItem('ShoppingCartList')) || []
        let oldPro = shoppingArr.find(item => item.id == proDetailPro.id)
        if (oldPro) {
            oldPro.num++
        } else {
            let newPro = {
                ...proDetailPro,
                num: 1,
                singlePrice: proDetailPro.price,
                state: false
            }
            shoppingArr.push(newPro)
        }
        localStorage.setItem('ShoppingCartList', JSON.stringify(shoppingArr))
        alert('商品以成功加入购物车！')
        location.href = '../pages/shoppingCart.html'
    })
}

// 商品详情下方的图片信息部分
function detailPic() {
    let id = proDetailId()
    $.ajax({
        url: 'http://www.xiongmaoyouxuan.com/api/detail',
        type: 'get',
        data: {
            id: id
        },
        success: function (data) {
            detailPicShow(data.data.detail.descContentList)
        },
        error: function (error) {
            alert("网络请求失败：" + error)
        }
    })
}

function detailPicShow(detailPicList) {
    let detailPic = detailPicList.map(item => {
        return `
                <div class="detailPicImg">
                    <img src="${item.image.url}" alt="">
                </div>
                `
    }).join('')
    $('#detailPic').html(detailPic)
}


// 各种方法的调用
getUserMessage()
unSearch()
searchPro()
hearderProNameToShowProNav()
proDetail()
detailPic()